//
//  ModelController.m
//  Sky
//
//  Created by chen on 16/6/28.
//  Copyright (c) 2016年 chen. All rights reserved.
//

#import "ModelController.h"

@interface ModelController ()

@property (strong,nonatomic) NSArray *cityNames;

@end

@implementation ModelController

-(instancetype)init
{
    self=[super init];
    if (self) {
        NSFileManager *filemanage=[NSFileManager defaultManager];
        NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *filePath=[path stringByAppendingPathComponent:@"SelectedCities.plist"];
        if ([filemanage fileExistsAtPath:filePath]) {
            self.cityNames=[NSArray arrayWithContentsOfFile:filePath];
        }else{
            self.cityNames=@[@"北京",@"上海",@"广州"];
            [self.cityNames writeToFile:filePath atomically:YES];
        }
        }
    return self;
}


-(DataViewController *)viewControllerAtIndex:(NSUInteger)index storyboard:(UIStoryboard *)storyboard
{
    if (([self.cityNames count]==0) || (index>=[self.cityNames count])) {
        return nil;
    }
    DataViewController *dataViewController=[[DataViewController alloc]init];
    dataViewController.pageIndex=index;
    dataViewController.cityString=self.cityNames[index];
    return dataViewController;
}

-(NSUInteger)indexOfViewController:(DataViewController *)viewController
{
    return viewController.pageIndex;
}

#pragma mark - page View Controller Data Source


-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSLog(@"Before");
    NSUInteger index=[self indexOfViewController:(DataViewController*)viewController];
    if (index==0 || index==NSNotFound) {
        return nil;
    }
    index --;
    return [self viewControllerAtIndex:index storyboard:viewController.storyboard];
}

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSLog(@"After");
    NSUInteger index=[self indexOfViewController:(DataViewController *)viewController];
    if (index==NSNotFound) {
        return nil;
    }
    index++;
    if (index==[self.cityNames count]) {
        return nil;
    }
    return [self viewControllerAtIndex:index storyboard:viewController.storyboard ];
}

-(void)refresh{
    NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath=[path stringByAppendingPathComponent:@"SelectedCities.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        self.cityNames=[NSArray arrayWithContentsOfFile:filePath];
    }

}

-(NSUInteger)count{
    NSLog(@"cityCount: %ld",self.cityNames.count);
    return self.cityNames.count;
}

@end
